package cn.ym.mall.dao.impl;

import cn.ym.mall.dao.GradeDao;
import cn.ym.mall.entity.Grade;
import cn.ym.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GradeDaoImpl implements GradeDao {
    QueryRunner queryRunner = new QueryRunner();
    /**
     * 根据会员id查询折扣
     *
     * @return
     */
    @Override
    public Grade getGradeBygrid(Integer grid) {
        Grade grade = new Grade();
        try {
            String sql = "select grdiscounts from ym_grade where grid=?;";
            grade = queryRunner.query(DruidUtils.getConnection(),sql,new BeanHandler<Grade>(Grade.class),grid);
        }catch (Exception e){
            e.printStackTrace();
        }
        return grade;
    }

    /**
     * 查询会员等级
     *
     * @return
     */
    @Override
    public List<Grade> getAllGrade() {
        List<Grade> gradeList = new ArrayList<>();
        try {
            String sql = "select * from ym_grade;";
            gradeList = queryRunner.query(DruidUtils.getConnection(),sql,new BeanListHandler<Grade>(Grade.class));
        }catch (Exception e){
            e.printStackTrace();
        }
        return gradeList;
    }

    /**
     * 修改会员折扣
     *
     * @param grade
     * @return
     */
    @Override
    public int updateGrade(Grade grade) {
        int num = 0;
        try {
            String sql = "update ym_grade set grdiscounts=? where grid=?;";
            num = queryRunner.update(DruidUtils.getConnection(),sql,grade.getGrdiscounts(),grade.getGrid());
        }catch (SQLException e){
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 通过grid删除会员
     *
     * @param grid
     * @return
     */
    @Override
    public int deleteGradeBygrid(Integer grid) {
        int num = 0;
        try {
            String sql = "delete from ym_grade where grid=?;";
            num = queryRunner.update(DruidUtils.getConnection(),sql,grid);
        }catch (SQLException e){
            e.printStackTrace();
        }
        return 0;
    }
}
